<template>
	<view class="order-manage">
		<!-- 顶部搜索及筛选区域 -->
		<view class="top-bar">
			<view class="cardform" labelPosition="left" v-model="activity">
				<view style="display: flex;margin-top: 20rpx;">
					<view style="margin-top: 15rpx;width: 100rpx;">标题：</view>
					<u--input placeholder="请输入内容" border="surround" v-model="activity.title" style="height: 40rpx;"></u--input>
				</view>
				<view style="display: flex;margin-top: 30rpx;">
					<view style="margin-top: 15rpx;width: 100rpx;">内容：</view>
					<u--textarea v-model="activity.content" placeholder="请输入内容"></u--textarea>
				</view>
				<view style="display: flex;margin-top: 30rpx;">
					<view style="margin-top: 15rpx;width: 100rpx;">电话：</view>
					<u--textarea v-model="activity.telephone" placeholder="请输入电话" style="height: 40rpx;"></u--textarea>
				</view>
				<view style="display: flex;margin-top: 30rpx;">
					<view style="margin-top: 15rpx;width: 100rpx;">原价：</view>
					<u--textarea v-model="activity.originalPrice" placeholder="输入原价" style="height: 40rpx;margin-right: 20rpx;"></u--textarea>
					<view style="margin-top: 15rpx;width: 120rpx;">折扣价：</view>
					<u--textarea v-model="activity.presentPrice" placeholder="输入折扣价" style="height: 40rpx;"></u--textarea>
				</view>
				<view style="display: flex;margin-top: 30rpx;">
					<view style="margin-top: 15rpx;width: 100rpx;">注意事项：</view>
					<u--textarea v-model="activity.note" placeholder="请输入注意事项"></u--textarea>
				</view>
				<view class="input-item">
					<u-form-item label="结束时间" borderBottom ref="item1" labelWidth="100rpx">
						<uni-datetime-picker type="date" v-model="activity.endTime" style="width: 530rpx;"></uni-datetime-picker>
					</u-form-item>
				</view>
				<view style="display: flex;margin-top: 30rpx;">
					<view style="margin-top: 15rpx;width: 100rpx;">图片：</view>
					<view @click="chooseImage('img')" class="upload-item">
						<template v-if="activity.img">
							<image class="uploaded-img" :src="activity.img" mode="aspectFill"></image>
							<view class="delete-icon" @click.stop="deleteImage('img')">×</view>
						</template>
						<template v-else>
							<image class="upload-icon" src="/static/icon-plus.png"></image>
							<text class="upload-text">上传照片</text>
						</template>
					</view>
				</view>
			</view>
			<button class="activity-btn" @click="getactivity()">
				发布
			</button>
		</view>
	</view>
</template>

<script>
	import {
		get,
		post
	} from '../../utils/request.js';
	export default {
		data() {
			return {
				activity:{
					title:'',
					content:'',
					originalPrice:'',
					presentPrice:'',
					telephone:'',
					note:'',
					img:'',
					endTime:''
				},
				fileList1: [],
				show: false,
			}
		},
		methods: {
			// 添加：删除图片
			deleteImage(type) {
				this.activity[type] = '';
			},
			
			chooseImage(type) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						const tempFile = res.tempFiles[0];
						const localPath = tempFile.path;
						// 根据类型保存到activity对象中
						this.activity[type] = localPath;
			
						// 尝试上传到服务器
						try {
							const uploadRes = await this.uploadFile(tempFile.path);
							if (uploadRes && uploadRes.startsWith('http')) {
								// 延迟更新为网络路径
								setTimeout(() => {
									this.activity[type] = uploadRes;
								}, 300);
							} else {
								throw new Error('网络路径无效，保留本地路径');
							}
						} catch (err) {
							uni.showToast({
								title: '图片上传失败',
								icon: 'none'
							});
						}
					}
				});
			},
			async uploadFile(filePath) {
				return new Promise((resolve, reject) => {
					const token = uni.getStorageSync('token') || '';
					uni.uploadFile({
						url: 'http://localhost/dev-api/file/upload',
						filePath: filePath,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + token,
						},
						formData: {},
						success: (res) => {
							if (res.statusCode === 200) {
								try {
									const response = JSON.parse(res.data);
									if (response.code === 200) {
										// 1. 适配后端返回的不同格式（根据实际返回调整）
										let imagePath = '';
										if (typeof response.data === 'string') {
											// 情况1：后端直接返回路径字符串（如 "/statics/xxx.jpg"）
											imagePath = response.data;
										} else if (response.data && response.data.url) {
											// 情况2：后端返回对象，路径在url字段（如 { url: "/statics/xxx.jpg" }）
											imagePath = response.data.url;
										} else {
											// 无法解析路径时直接报错
											reject(new Error('无法从后端响应中获取图片路径'));
											return;
										}
			
										// 2. 拼接完整URL（确保以http开头且格式正确）
										const baseUrl = 'http://127.0.0.1:9300';
										let fileUrl = '';
										if (imagePath.startsWith('http')) {
											// 若后端已返回完整URL，直接使用
											fileUrl = imagePath;
										} else {
											// 拼接baseUrl（注意处理斜杠，避免重复或缺失）
											fileUrl = baseUrl + (imagePath.startsWith('/') ? '' :
												'/') + imagePath;
										}
										resolve(fileUrl);
									} else {
										reject(new Error(`上传失败：${response.msg || '未知错误'}`));
									}
								} catch (e) {
									reject(new Error(`解析响应失败：${e.message}`));
								}
							} else {
								reject(new Error(`上传失败，状态码：${res.statusCode}`));
							}
						},
						fail: (err) => {
							reject(new Error(`请求失败：${err.errMsg}`));
						}
					});
				});
			},
			// uView上传组件处理
			async afterRead(event) {
				const lists = [].concat(event.file);
				const name = event.name;
			
				lists.forEach((item, index) => {
					this[`fileList${name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
			
					this.uploadFile(item.url).then(res => {
						if (res) {
							this[`fileList${name}`][index].status = 'success';
							this[`fileList${name}`][index].url = res;
							this.activity.img = res; // 保存图片URL到activity对象
						} else {
							this[`fileList${name}`][index].status = 'failed';
							this[`fileList${name}`][index].message = '上传失败';
						}
					});
				});
			},
			
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			async getactivity(){
				const today = new Date();
				console.log(today)
				this.activity.time=today
				this.activity.status=0
				this.activity.mid=uni.getStorageSync('merchant').id
				this.activity.publisher=uni.getStorageSync('merchant').name
				await post('/dev-api/system/purchase',this.activity)
				console.log(this.activity)
			},
			confirm(e){
				this.show=false
				this.activity.endTime=e
				console.log(e)
			}
		}
	}
</script>

<style>
	.order-manage {
		background-color: #f5f5f5;
		min-height: 100vh;
		height: 1500rpx;
	}

	/* 顶部搜索及筛选 */
	.top-bar {
		padding: 10px;
		background-color: #2979ff;
		height: 200rpx;
	}
	
	.input-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		box-sizing: border-box;
		border-bottom: 1rpx solid #eee;
	}

	.cardform {
		width: 90%;
		padding-left: 5%;
		padding-right: 5%;
		border-radius: 15rpx;
		height: 1200rpx;
		padding-top: 15rpx;
		background-color: white;
		padding-bottom: 10rpx;
	}

	.activity-btn {
		background-color: #2979ff;
		color: white;
		width: 70%;
		border-radius: 40rpx;
		margin-top: 30rpx;
	}
	.uploaded-img {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}
	.delete-icon {
		position: absolute;
		top: 5rpx;
		right: 5rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
	}
	
	.picker {
		flex: 1;
	}
	
	/* 新增图片上传样式 */
	.upload-item {
		width: 200rpx;
		height: 200rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		border: 1rpx dashed #ccc;
		position: relative;
		overflow: hidden;
	}
	.upload-icon {
		width: 60rpx;
		height: 60rpx;
		margin-bottom: 10rpx;
	}
	.upload-text {
		font-size: 24rpx;
		color: #999;
	}
</style>
    